import React from "react";
import { TouchableOpacity, View } from "react-native-ui-lib";
import { commonStyles } from "../../configs/commonStyle";
import NavigationBar from "../common/NavigationBar";
import BasePage from "../BasePage";
import { windowWidth } from "../../configs/platform";
import ListEmpty from "../common/ListEmpty";
import { TabBar, TabBarIndicator, TabView } from "react-native-tab-view";
import ViewUtils from "../../utils/ViewUtils";
import ComplaintOrderList from "./ComplaintOrderList";
import DateFilter from "../components/DateFilter";
import moment from "moment";
import { StyleSheet, Text } from "react-native";
import { Icon } from "../components";
import PickerTypeDialog from "../common/PickerTypeDialog";

const pickerData = ["全部", "未申诉", "申诉成功", "申诉失败"];
const ordStates = ["", -1, 2, 3];
/**
 * 投诉订单
 */
export default class ComplaintOrderMgr extends BasePage {

  constructor(props) {
    super(props);
    let startOfWeek = moment().startOf("week");
    let endOfWeek = moment().endOf("week");
    let start = (moment(startOfWeek).format("YYYY-MM-DD"));
    let end = (moment(endOfWeek).format("YYYY-MM-DD"));
    this.complaintList= [];
    this.state = {
      index: 0,
      routes: [
        { key: "all", title: "超时退款", value: 1, api: api.listOrderRefund },
        { key: "need", title: "超时退订", value: 2, api: api.listOrderUnsubscribe },
        { key: "had", title: "投诉工单", value: 3, api: api.listOrdercomplaint },
      ],
      delyStartTime: start,
      delyEndTimeEnd: end,
      ratio: "0%",
      countall: 0,
      count: 0,
      selectType: 0,
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.loadData();
  }

  loadData = () => {
    const { delyStartTime, delyEndTimeEnd } = this.state;
    let params = {
      token: global.token,
      delyStartTime: `${delyStartTime} 00:00:00`,
      delyEndTimeEnd: `${delyEndTimeEnd} 23:59:59`,
      showLoading: true,
    };
    axios.get(api.totalOrderComplain, { params })
      .then(res => {
        logger("订单详情", res);
        this.setState({
          countall: res.countall || 0,
          ratio: res.ratio || "0%",
          count: res.count || 0,
        });
      })
      .catch(e => {
        logger("error", e);
      });
  };

  renderTabBar = (props) => {
    return (
      <View style={{ backgroundColor: "white", marginBottom: 8 }}>
        <TabBar
          {...props}
          style={{ backgroundColor: "white", elevation: 0, alignSelf: "center", height: 45 }}
          activeColor={"#F9D63B"}
          inactiveColor={"#6F6F6F"}
          scrollEnabled
          tabStyle={{ width: windowWidth / 4 }}
          labelStyle={{}}
          renderIndicator={indicatorProps => {
            const width = indicatorProps.getTabWidth(this.state.index);
            return <TabBarIndicator {...indicatorProps} width={30}
                                    style={{ left: (width - 30) / 2, backgroundColor: "#F9D63B" }} />;
          }}
        />
      </View>
    );
  };

  renderHeader = () => {
    const { count, countall, ratio } = this.state;
    return (
      <View marginH-15 marginB-10>
        <Text style={commonStyles.text_black}>您总共配送<Text style={{ color: "#4A90E2" }}>{countall}</Text>单，投诉<Text
          style={{ color: "#EC808D" }}>{count}</Text>单，投诉率<Text
          style={{ color: "#EC808D" }}>{ratio}</Text></Text>
      </View>
    );
  };

  loadAllData=()=>{
    const { delyStartTime, delyEndTimeEnd } = this.state;
    this.loadData();
    this.state.routes.map(route => {
      if (this.complaintList[route.key] && this.complaintList[route.key].loadByDate) {
        this.complaintList[route.key].loadByDate(delyStartTime, delyEndTimeEnd);
      }
    });
  }

  render() {
    const { delyStartTime, delyEndTimeEnd, selectType } = this.state;
    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationBar
          title={"投诉订单"}
          backgroundColor={"transparent"}
          leftButton={ViewUtils.getLeftButton(() => this._onBackPress())}
          rightButton={ViewUtils.getRightImgTextBtn('reload1','',() => this.loadAllData(),16)}
        />
        <View style={commonStyles.container}>
          <View row centerV>
            <DateFilter defaultType={1} onQueryClick={(delyStartTime, delyEndTimeEnd) => this.setState({
              delyStartTime,
              delyEndTimeEnd,
            }, () => this.loadAllData())} />
            <TouchableOpacity activeOpacity={1} style={styles.typeWrap}
                              onPress={() => this.pickerOrderTypeDialog.show(selectType, pickerData)}>
              <View marginR-3>
                <Text numberOfLines={1} style={commonStyles.text_black}>{pickerData[selectType]}</Text>
              </View>
              <Icon type="AntDesign" name="down" size={12} color={"#CCCCCC"} />
            </TouchableOpacity>
          </View>
          {
            this.renderHeader()
          }
          <TabView
            lazy
            navigationState={this.state}
            renderScene={({ route }) => <ComplaintOrderList
                                                            ref={r => this.complaintList[route.key] = r}
                                                            ordState={ordStates[selectType]}
                                                            delyStartTime={delyStartTime}
                                                            delyEndTimeEnd={delyEndTimeEnd}
                                                            relationType={route.value}
                                                            api={route.api} />}
            initialLayout={{ width: windowWidth }}
            onIndexChange={(index) => this.setState({ index })}
            renderTabBar={this.renderTabBar}
            renderLazyPlaceholder={() => <ListEmpty showEmpty={true} />}
          />
        </View>
        <PickerTypeDialog ref={r => this.pickerOrderTypeDialog = r}
                               onChecked={(selectType) => this.setState({ selectType }, () => {
                                 this.state.routes.map(route => {
                                   if (this.complaintList[route.key] && this.complaintList[route.key].loadByState) {
                                     this.complaintList[route.key].loadByState(ordStates[selectType]);
                                   }
                                 });
                               })} />
      </View>
    );
  }
}


const styles = StyleSheet.create({
  typeWrap: {
    flexDirection: "row",
    alignItems: "center",
    width: 90,
    height: 40,
    justifyContent: "space-between",
    borderRadius: 4,
    borderWidth: 1,
    borderColor: "#CCCCCC",
    paddingHorizontal: 10,
    backgroundColor: "white",
  },
});
